/*
 * @Description: 遮罩层
 * @version: 1.0.0
 * @Author: Rattenking
 * @Date: 2022-10-19 14:56:57
 * @LastEditors: Rattenking
 * @LastEditTime: 2022-10-21 14:29:17
 */

import React, { Component } from "react";
import { View } from "@tarojs/components";
import './index.scss';

class RuiOverlay extends Component {
  constructor(props) {
    super(props);
    this.state = {
      animShow: false
    }
  }
  // 监听传入的 isOpened 值是 true 时，执行渐入动画
  UNSAFE_componentWillReceiveProps(nextProps){
    const { isOpened } = nextProps;
    if (isOpened) { 
      this.animShow();
    }
  }
  // 影藏遮罩层渐出动画
  animHide () {
    this.setState({
      animShow: false
    })
  }
  // 显示遮罩层渐入动画
  animShow () {
    let timer = setTimeout(() => {
      this.setState({
        animShow: true
      })
      clearTimeout(timer);
    }, 200)
  }
  // 关闭遮罩层，注意先执行渐出动画，完成后再执行关闭遮罩层的回调
  onHide () {
    let { onClose, duration } = this.props;
    if (typeof onClose === 'function') {
      this.animHide();
      let timer = setTimeout(() => {
        onClose();
        clearTimeout(timer);
      },duration ? duration : 300)
    }
  }
  render () { 
    let {
      opacity,
      duration,
      zIndex,
      position = "center",
      isOpened,
      children,
    } = this.props;
    let { animShow } = this.state;
    return <React.Fragment>
      {
        isOpened ?
          <View
            className="rui-overlay-component-content"
            onClick={e => {e.stopPropagation();return;}}>
            <View
              className="rui-mask-layer rui-fade-enter-active"
              onClick={this.onHide.bind(this)}
              style={`
                z-index:${ zIndex ? zIndex : 1026 };
                opacity:${animShow ? 1 : 0};
                transition-duration: ${duration ? duration : 300}ms;
                background-color: rgba(0, 0, 0, ${ opacity ? opacity : '0.4' });
              `}>
              <View
                className={`rui-mask-content rui-${ position }`}
                onClick={e => { e.stopPropagation(); return; }}>
                {children}
              </View>
            </View>
          </View>
          :
          <React.Fragment />
      }
    </React.Fragment>;
  }
}

export default RuiOverlay;